package com.meixiang.fragment.shopping;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okhttputils.model.HttpParams;
import com.lzy.okhttputils.request.BaseRequest;
import com.meixiang.R;
import com.meixiang.activity.homes.service.ShowPictureActivity;
import com.meixiang.activity.homes.shopping.GoodsDetailActivity;
import com.meixiang.activity.homes.shopping.PrivilegeSuitActivity;
import com.meixiang.dialog.LoadingDialog;
import com.meixiang.entity.shopping.GoodsDetailEntity;
import com.meixiang.entity.shopping.GoodsGroupEntity;
import com.meixiang.entity.shopping.result.GoodsDetailResult;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseFragment;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.TextViewUtil;
import com.meixiang.view.BannerLayout;
import com.meixiang.view.ImageGallery;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 商品详情信息
 *
 * @author LZRUI
 */
public class GoodsDetailInfoFragment extends BaseFragment implements View.OnClickListener {

    @Bind(R.id.vs_pic)
    ViewStub viewStubPic; // 图片轮播
    @Bind(R.id.fl_pic)
    FrameLayout flPic; // 包裹轮播图的布局
    @Bind(R.id.tv_goods_name)
    TextView tvGoodsName; // 商品名称
    @Bind(R.id.tv_new_price)
    TextView tvNewPrice; // 商品折后价格
    @Bind(R.id.tv_old_price)
    TextView tvOldPrice; // 商品原价
    @Bind(R.id.tv_goods_type)
    TextView tvGoodsType; // 商品类型
    @Bind(R.id.tv_express)
    TextView tvExpress; // 商品快递方式（包邮）
    @Bind(R.id.tv_sell_num)
    TextView tvSellNum; //  销售数量
    @Bind(R.id.tv_send_address)
    TextView tvSendAddress; // 发送地址
    @Bind(R.id.vs_privilege_suit)
    ViewStub vsPrivilegeSuit; // 优惠套装
    @Bind(R.id.tv_goods_quality)
    TextView tvGoodsQuality; // 正品保障
    @Bind(R.id.tv_goods_brand)
    TextView tvGoodsBrand; // 品牌授权
    @Bind(R.id.tv_goods_exchange)
    TextView tvGoodsExchange; //7天包退

    private TextView tvPicNumHint;
    private View rootView;
    private String goodsId;
    private static String GOODS_ID = "goodsId";
    private FavoriteListener favoriteListener;
    private LoadingDialog loadingDialog;

    public void setFavoriteListener(FavoriteListener favoriteListener) {
        this.favoriteListener = favoriteListener;
    }

    public static GoodsDetailInfoFragment newInstance(String goodsId) {
        GoodsDetailInfoFragment fragment = new GoodsDetailInfoFragment();
        Bundle bundle = new Bundle();
        bundle.putString(GOODS_ID, goodsId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            goodsId = getArguments().getString(GOODS_ID);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_goods_detail_info, container, false);
        ButterKnife.bind(this, rootView);
        super.onCreateView(inflater, container, savedInstanceState);
        return rootView;
    }

    @Override
    protected void initTitle() {

    }

    @SuppressWarnings("unchecked")
    @Override
    protected void initView() {
        LinearLayout.LayoutParams cParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, Tool.getWindowHeight(getActivity()) / 2);
        flPic.setLayoutParams(cParams);
        loadingDialog = new LoadingDialog(activity);
    }

    @Override
    protected void setData() {
        getGoodsDetailData();
    }

    /**
     * 设置数据
     *
     * @param goodsDetailResult
     */
    public void initData(final GoodsDetailResult goodsDetailResult) {
        if (goodsDetailResult == null) {
            Toast.makeText(activity, "数据获取失败", Toast.LENGTH_SHORT).show();
            return;
        }
        // 优惠套装
        if (goodsDetailResult.isGroup()) {
            vsPrivilegeSuit.inflate();
            TextView tvSaveMoney = (TextView) rootView.findViewById(R.id.tv_save_money);
            GoodsGroupEntity goodsGroupEntity = goodsDetailResult.getGoodsGroup();
            tvSaveMoney.setText(String.format(getString(R.string.save_money), goodsGroupEntity.getBenefit()));
            ImageGallery imageGallery = (ImageGallery) rootView.findViewById(R.id.img_gallery);
            imageGallery.setMargin(0, 5, 0, 5);
            imageGallery.setData(Arrays.asList(goodsGroupEntity.getGoodsGroupImage()), true);
            imageGallery.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), PrivilegeSuitActivity.class);
                    intent.putExtra(PrivilegeSuitActivity.GOODS_ID, goodsDetailResult.getGoodsId());
                    startActivity(intent);
                }
            });
        }

        GoodsDetailEntity goodsDetailEntity = goodsDetailResult.getGoods();
        if (goodsDetailEntity == null) return;
        final ArrayList<String> urls = (ArrayList<String>) goodsDetailEntity.getGoodsImageMore();
        if (urls != null) {
            int len = urls.size();
            if (len > 0) {
                viewStubPic.inflate();
                BannerLayout cycleViewPager = (BannerLayout) rootView.findViewById(R.id.cycle_view_pager);
                tvPicNumHint = (TextView) rootView.findViewById(R.id.tv_pic_num_hint);
                tvPicNumHint.setText("1" + "/" + len);
                cycleViewPager.setViewUrls(urls).setScrollListener(new BannerLayout.PageScrollListener() {
                    @Override
                    public void onPageScroll(int position, int totalCount) {
                        tvPicNumHint.setText((position + 1) + "/" + totalCount);
                    }
                });
                cycleViewPager.setOnBannerItemClickListener(new BannerLayout.OnBannerItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        Intent intent = new Intent(activity, ShowPictureActivity.class);
                        intent.putStringArrayListExtra("urls", urls);
                        intent.putExtra("position", position);
                        activity.startActivity(intent);
                    }
                });
            }
        }

        TextViewUtil.setDiffSizeText(tvNewPrice, String.format(activity.getString(R.string.price_str), goodsDetailEntity.getGoodsStorePrice()), 0, 1, 16);
        TextViewUtil.setStrickoutText(tvOldPrice, String.format(activity.getString(R.string.price_str), goodsDetailEntity.getGoodsMarketPrice()));
        tvExpress.setText(String.format(getString(R.string.express), goodsDetailEntity.getGoodsTransfreeCharge()));
        tvSellNum.setText(String.format(getString(R.string.sell_num), goodsDetailEntity.getSalenum()));
        tvSendAddress.setText(String.format(getString(R.string.send_address), goodsDetailEntity.getCityName()));
        tvGoodsName.setText(goodsDetailEntity.getGoodsName());
        tvGoodsType.setText(goodsDetailResult.getStoreName() + "商品");
        tvGoodsQuality.setText((null == goodsDetailResult.getNote() || TextUtils.isEmpty(goodsDetailResult.getNote()[0])) ? "正品保障" : goodsDetailResult.getNote()[0]);
        tvGoodsBrand.setText((null == goodsDetailResult.getNote() || TextUtils.isEmpty(goodsDetailResult.getNote()[1])) ? "品牌授权" : goodsDetailResult.getNote()[1]);
        tvGoodsExchange.setText((null == goodsDetailResult.getNote() || TextUtils.isEmpty(goodsDetailResult.getNote()[2])) ? "7天包退" : goodsDetailResult.getNote()[2]);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onClick(View v) {

    }

    /**
     * 获取详情信息
     */
    private void getGoodsDetailData() {
        HttpParams params = new HttpParams();
        params.put("goodsId", goodsId);

        Log.i("lzrtest", "商品详情：params " + params);

        HttpUtils.post(Config.GOODS_DETAIL, GoodsDetailActivity.TAG, params, new HttpCallBack(activity) {

            @Override
            public void onBefore(BaseRequest request) {
                if (loadingDialog != null && !loadingDialog.isShowing()) loadingDialog.show();
            }

            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                GoodsDetailResult goodsDetailResult = AbJsonUtil.fromJson(result.toString(), GoodsDetailResult.class);
                if (favoriteListener != null) {
                    favoriteListener.checkCollect(goodsDetailResult.isFavorite(), true);
                }
                initData(goodsDetailResult);
                ((GoodsDetailActivity)activity).setIsHeadQuarter(goodsDetailResult.getIsHeadQuarter());
            }

            @Override
            public void onError(String code, String message) {
                Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                if (loadingDialog != null && loadingDialog.isShowing()) loadingDialog.dismiss();
            }
        });
    }

    /**
     * 收藏初始状态回调
     */
    public interface FavoriteListener {
        void checkCollect(boolean isCollect, boolean isFirst);
    }

}
